//
//  XYHomeStatusListViewModel.swift
//  WeiboSourceCode
//
//  Created by 周星宇 on 16/1/1.
//  Copyright © 2016年 cn.weibo. All rights reserved.
//  负责首页的数据请求  给首页提供数据

import UIKit
import SDWebImage
class XYHomeStatusListViewModel: NSObject {
    
    var statusList: [XYStatusViewModel]?
    
    static let sharedStatusListViewModel: XYHomeStatusListViewModel = XYHomeStatusListViewModel()
    
    func loadData(isPulling: Bool,completion: (isSuccess:Bool,count:Int) -> ()) {
        
        var maxId: Int64 = 0
        var sinceId: Int64 = 0
        if isPulling {
            
            maxId = statusList?.last?.status?.id ?? 0
            if maxId > 0 {
                maxId -= 1
            }
        }else {
            // 下拉刷新
            sinceId = statusList?.first?.status?.id ?? 0
            
        }
        
        XYHTTPTool.sharedHttpTool.requestLoadHomeData(maxId,sinceId: sinceId) { (response, error) -> () in
            if error != nil {
                completion(isSuccess: false,count: 0)
                print(error)
                return
            }
            // 取出返回的数据
            guard let dict = response as? [String: AnyObject] else {
                completion(isSuccess: false,count:0)
                return
            }
            if self.statusList == nil {
                
                self.statusList = [XYStatusViewModel]()
            }
            // 字典转模型( 取出字典中的微博数据 并且强转为 对应字典类型的数组
            let statusesArray = dict["statuses"]! as! [[String: AnyObject]]
            var tempArray = [XYStatusViewModel]()
            // 遍历数组 转模型
            for statusDict in statusesArray {
                let status = XYStatus(dict: statusDict)
                let statusViewModel = XYStatusViewModel()
                statusViewModel.status = status
                tempArray.append(statusViewModel)
            }
            if isPulling {
                self.statusList! += tempArray
            }else {
                self.statusList = tempArray + self.statusList!
            }
            
            
           // 缓存单张图片
            self.cacheSingleImage(tempArray, completion: completion)
            // 通知控制器刷新数据
//            completion(isSuccess: true)
        }
    }
    private func cacheSingleImage(dataArray: [XYStatusViewModel], completion: (isSuccess:Bool,count: Int) -> ()){
        // 手动实现当所有图片下载到缓存中  后 在完成回调 (在刷新数据前 完成所有逻辑)
        let group = dispatch_group_create()
        for viewModel in dataArray{
            
            if viewModel.picUrls?.count != 1{
                
                continue
            }
            // 取出地址 并开始缓存 添加到队列组中
            let urlString = viewModel.picUrls!.first!.thumbnail_pic!
            let url = NSURL(string: urlString)
            // 入组 执行下列操作后会开始监听后续的block
            dispatch_group_enter(group)
            SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (image, error, _, _, _) -> Void in
                // 下载完毕后出组操作
                dispatch_group_leave(group)
            })
        }
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            // 回到主线程 完成请求成功的回调
            completion(isSuccess: true,count: dataArray.count)
        }
        
    }
}
